package com.lhfeiyu.action.front.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.Bonus;
import com.lhfeiyu.po.BonusDetail;
import com.lhfeiyu.po.base.BaseChat;
import com.lhfeiyu.po.base.BaseFans;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserFund;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.BonusDetailService;
import com.lhfeiyu.service.BonusService;
import com.lhfeiyu.service.base.BaseChatService;
import com.lhfeiyu.service.base.BaseFansService;
import com.lhfeiyu.service.base.BaseUserFundService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;

@Controller
public class BonusAction {
	@Autowired
	private BaseUserFundService userFundService;
	@Autowired
	private BonusService bonusService;
	@Autowired
	private BonusDetailService bonusDetailService;
	@Autowired
	private BaseChatService chatService;
	@Autowired
	private BaseFansService fansService;
	@Autowired
	private AuthCheckService authCheckService;
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/bonus")
	public ModelAndView bonusIndex(ModelMap modelMap,HttpServletRequest request,
			@RequestParam(required=false) String from,
			@RequestParam(required=false) String r) {
		String path = Page.bonusIndex;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/bonus";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", user.getId());
			List<BaseUserFund> userFundList = userFundService.selectListByCondition(map);
			if(null != userFundList && userFundList.size()>0){
				modelMap.put("avaliableMoney", userFundList.get(0).getAvaliableMoney());
			}
			if(Check.isNotNull(from))json.put("from", from);
			modelMap.put("paramJson", json);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/bonus", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/randomBonus")
	public ModelAndView randomBonus(ModelMap modelMap,HttpServletRequest request,
			@RequestParam(required=false) String from,
			@RequestParam(required=false) String r) {
		String path = Page.randomBonus;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/randomBonus";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			if(Check.isNotNull(from))json.put("from", from);
			modelMap.put("paramJson", json);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/randomBonus", modelMap);
		}
		
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/commonBonus")
	public ModelAndView commonBonus(ModelMap modelMap,HttpServletRequest request,
			 @RequestParam(required=false) String from,
			 @RequestParam(required=false) String r,
			 @RequestParam(required=false) String rd) {
		String path = Page.commonBonus;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/commonBonus";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			if(Check.isNotNull(from))json.put("from", from);
			modelMap.put("paramJson", json);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/commonBonus", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/bonusReceived")
	public ModelAndView bonusReceived(ModelMap modelMap, HttpSession session
			,@RequestParam(required=false) String r,HttpServletRequest request) {
		String path = Page.bonusReceived;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(session);
			if(null == user){
				String jumpUrl = "/bonusReceived";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			String totalBonusMoney = bonusDetailService.selectSumByCondition(map);
			Integer totalBonusNum = bonusDetailService.selectCountByCondition(map);
			Integer totalSendBonusNum = bonusService.selectCountByCondition(map);
			modelMap.put("totalBonusMoney", totalBonusMoney);
			modelMap.put("totalBonusNum", totalBonusNum);
			modelMap.put("totalSendBonusNum", totalSendBonusNum);
			modelMap.put("user", user);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/bonusReceived", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/bonusSend")
	public ModelAndView bonusSend(ModelMap modelMap, HttpSession session
			,@RequestParam(required=false) String r,HttpServletRequest request) {
		String path = Page.bonusSend;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(session);
			if(null == user){
				String jumpUrl = "/bonusSend";
				if(null != r)jumpUrl += "?r="+r;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			String totalBonusMoney = bonusService.selectSumByCondition(map);
			int totalSendBonusMoney = bonusService.selectCountByCondition(map);
			map.remove("userId");
			map.put("bossId", userId);
			map.put("dealt", 1);//状态为已领
			String dealBonusMoney = bonusDetailService.selectSumByCondition(map);//已领
			
			modelMap.put("totalBonusMoney", totalBonusMoney);
			modelMap.put("totalSendBonusMoney", totalSendBonusMoney);
			modelMap.put("dealBonusMoney", dealBonusMoney);
			modelMap.put("user", user);
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载发出的红包页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/bonusDetail/{bonusId}")
	public ModelAndView bonusDetail(ModelMap modelMap, HttpSession session
			,@PathVariable Integer bonusId
			,@RequestParam(required=false) String r,HttpServletRequest request) {
		String path = Page.bonusDetail;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(session);
			if(null == user){
				String jumpUrl = "/bonusDetail/"+bonusId;
				if(null != r)jumpUrl += "?r="+r;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("bonusId", bonusId);
			List<Bonus> bList = bonusService.selectListByCondition(map);
			if(null != bList && bList.size()>0){
				Bonus bonus = bList.get(0);
				modelMap.put("bonus", bonus);
				modelMap.put("bonusId", bonusId);
				Integer bossId = bonus.getUserId();
				if(null != bossId && (bossId.intValue() == userId.intValue())){
					modelMap.put("boss", 1);
				}
				map.put("dealt", 1);
				String dealMoney = bonusDetailService.selectSumByCondition(map);
				int dealCount = bonusDetailService.selectCountByCondition(map);
				if(null == dealMoney || "".equals(dealMoney))dealMoney = "0";
				modelMap.put("dealMoney", dealMoney);
				modelMap.put("dealCount", dealCount);
				map.clear();
				map.put("userSerial", user.getSerial());
				map.put("bonusId", bonusId);
				List<BonusDetail> bonusList = bonusDetailService.selectListByCondition(map);
				if(null != bonusList && bonusList.size()>0){
					modelMap.put("myBonus", bonusList.get(0));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载红包详情页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	/*@RequestMapping(value="/bonusReceivedDetail")
	public ModelAndView bonusReceivedDetail(ModelMap modelMap, HttpSession session) {
		String path = PagePath.bonusReceivedDetail;
		try{
			User user = ActionUtil.checkSession4User(session);
			if(null == user){
				String jumpUrl = "/bonusReceivedDetail";
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
		}catch(Exception e){
			e.printStackTrace();
			path = PagePath.error;
			logger.error("LH_ERROR_加载接收的红包详情页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/bonusSendDetail")
	public ModelAndView bonusSendDetail(ModelMap modelMap, HttpSession session) {
		String path = PagePath.bonusSendDetail;
		try{
			User user = ActionUtil.checkSession4User(session);
			if(null == user){
				String jumpUrl = "/bonusSendDetail";
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
		}catch(Exception e){
			e.printStackTrace();
			path = PagePath.error;
			logger.error("LH_ERROR_加载发出的红包详情页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}*/
	
	@ResponseBody
	@RequestMapping(value="/getBonusReceivedList", method=RequestMethod.POST)
	public JSONObject getBonusReceivedList(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = ActionUtil.getAllParam(request);
			map.put("userId", userId);
			List<BonusDetail> bonusDetailList = bonusDetailService.selectListByCondition(map);
			json.put("rows", bonusDetailList);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载收到的红包列表数据出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getBonusSendList", method=RequestMethod.POST)
	public JSONObject getBonusSendList(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = ActionUtil.getAllParam(request);
			map.put("userId", userId);
			List<Bonus> bonusList = bonusService.selectListByCondition(map);
			json.put("rows", bonusList);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载发出的红包列表数据出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getBonusDetailList", method=RequestMethod.POST)
	public JSONObject getBonusDetailList(HttpServletRequest request
			,@RequestParam Integer bonusId) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Map<String, Object> map = ActionUtil.getAllParam(request);
			//Integer userId = user.getId();
			//map.put("userId", userId);
			map.put("bonusId", bonusId);
			map.put("dealt", 1);
			List<BonusDetail> bonusDetailList = bonusDetailService.selectListByCondition(map);
			json.put("rows", bonusDetailList);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载红包详细列表数据出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateBonusDetailMsg", method=RequestMethod.POST)
	public JSONObject updateBonusDetailMsg(HttpServletRequest request
			,@RequestParam Integer bonusId, @RequestParam String msg) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = ActionUtil.getAllParam(request);
			map.put("userId", userId);
			map.put("bonusId", bonusId);
			List<BonusDetail> bonusDetailList = bonusDetailService.selectListByCondition(map);
			if(null != bonusDetailList && bonusDetailList.size()>0){
				BonusDetail bd = bonusDetailList.get(0);
				BonusDetail newBD = new BonusDetail();
				newBD.setId(bd.getId());
				newBD.setMsg(msg);
				bonusDetailService.updateByPrimaryKeySelective(newBD);
			}
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载红包详细列表数据出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addBonus", method=RequestMethod.POST)
	public JSONObject addBonus(HttpServletRequest request,@ModelAttribute Bonus bonus
			, @RequestParam String payPass, @RequestParam(required=false) Double eachMoney) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			BigDecimal totalMoney = bonus.getTotalMoney();
			Integer count = bonus.getCount();
			Integer typeId = bonus.getTypeId();
			String msg = bonus.getMsg();
			if(null == totalMoney || totalMoney.doubleValue()<1){
				return Result.failure(json, "红包金额不正确", "totalMoney_invalid");
			}
			if(null == count || count.intValue()<1){
				return Result.failure(json, "红包数量不正确", "count_invalid");
			}
			if(typeId!=1){
			if(null == eachMoney || eachMoney <= 0){
				return Result.failure(json, "单个红包金额不正确", "eachMoney_invalid");
			}
			}
			if(Check.isNull(msg)){
				msg = "恭喜发财，大吉大利";
			}
			if(null == typeId || typeId != 2 ){
				typeId = 1;
			}else{
				double money = eachMoney * bonus.getCount();
				if(null == eachMoney || bonus.getTotalMoney().doubleValue() != money){
					return Result.failure(json, "单个红包金额不正确", "eachMoney_invalid");
				}
			}
			Date date = new Date();
			//bonus.setDealTime(date);
			bonus.setMsg(msg);
			bonus.setTypeId(typeId);
			bonus.setCreatedAt(date);
			//部分字段是在bonusService.addBonus方法中设置的//验证密码并扣款
			json = bonusService.addBonus(payPass, user, bonus, eachMoney, date, json);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_添加红包出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/receiveBonus", method=RequestMethod.POST)//
	public JSONObject receiveBonus(HttpServletRequest request,
			@RequestParam Integer bossId,
			@RequestParam(required=false) Integer isGroupBonus,
			//@RequestParam(required=false) Integer bonusLinkType,//1专场红包
			//@RequestParam(required=false) Integer bonusLinkId,
			@RequestParam(required=false) Integer id) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			//Integer userId = user.getId();
			//String username = user.getUsername();
			if(null == isGroupBonus){
				json = bonusService.receiveBonus(bossId, user, json, id);
			}else{
				/*if(null == bonusLinkType || null != bonusLinkId){
					return Result.failure(json, "该红包链接不正确", "bonusLink_null");
				}*/
				json = bonusService.receiveGroupBonus(bossId, user, json);//, bonusLinkType, bonusLinkId
			}
			json.put("username", user.getUsername());
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_接收红包出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addBonusChat", method=RequestMethod.POST)
	public JSONObject addBonusChat(HttpServletRequest request,@ModelAttribute BaseChat chat) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			int userId = user.getId();
			Integer receiverId = chat.getReceiverId();
			if(null == receiverId){
				return Result.failure(json, "参数不足,无法发送消息", "receiverId_null");
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("notDeal", 1);
			List<Bonus> bonusList = bonusService.selectListByCondition(map);
			if(null == bonusList || bonusList.size() <= 0){
				return Result.failure(json, "已经没有可以发送的红包了，请到个人中心添加红包", "bonus_lack");
			}
			Date d = new Date();
			chat.setSerial(CommonGenerator.getSerialByDate("cs"));
			chat.setCreatedAt(d);
			chat.setCreatedBy(user.getUsername());
			chat.setSendTime(d);
			chat.setSenderId(userId);
			chat.setTypeId(2);
			chat.setMainStatus(1);
			chat.setContent("红包");//后期可考虑让用户输入
			chatService.insertSelective(chat);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_接收红包出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addBatchBonusChat", method=RequestMethod.POST)
	public JSONObject addBatchBonusChat(HttpServletRequest request,@RequestParam Integer typeId) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			int userId = user.getId();
			String username = user.getUsername();
			String idFlag;
			String tip;
			if(typeId == 1){// 我关注的
				idFlag = "fansId";
				tip = "您目前没有关注的用户，无法群发红包";
			}else if(typeId == 2){// 关注我的
				idFlag = "userId";
				tip = "目前还没有用户关注您，无法群发红包";
			}else{
				return Result.failure(json, "参数不正确", "typeId_invalid");
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("notDeal", 1);
			List<Bonus> bonusList = bonusService.selectListByCondition(map);
			if(null == bonusList || bonusList.size() <= 0){
				return Result.failure(json, "已经没有可以发送的红包了，请到个人中心添加红包", "bonus_lack");
			}
			Date d = new Date();
			map.clear();
			map.put(idFlag, userId);
			List<BaseFans> fansList = fansService.selectListByCondition(map);
			if(Check.isNotNull(fansList)){
				List<BaseChat> chatList = new ArrayList<BaseChat>(fansList.size());
				for(BaseFans f: fansList){
					BaseChat chat = new BaseChat();
					chat.setSerial(CommonGenerator.getSerialByDate("cs"));
					chat.setCreatedAt(d);
					chat.setCreatedBy(username);
					chat.setSendTime(d);
					chat.setSenderId(userId);
					chat.setTypeId(2);
					chat.setMainStatus(1);
					chat.setContent("红包");//后期可考虑让用户输入
					if(typeId == 1){// 我关注的
						chat.setReceiverId(f.getUserId());
					}else{
						chat.setReceiverId(f.getFansId());
					}
					chatList.add(chat);
				}
				chatService.insertBatch(chatList);
			}else{
				return Result.failure(json, tip, tip);
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_接收红包出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/checkBonusRemain", method=RequestMethod.POST)
	public JSONObject checkBonusRemain(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			int userId = user.getId();
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("notDeal", 1);
			int count = bonusService.selectCountByCondition(map);
			if(count <= 0){
				return Result.failure(json, "已经没有可以发送的红包了，请到个人中心添加红包", "bonus_lack");
			}
			json.put("userId", userId);
			json.put("username", user.getUsername());
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_检查是否有剩余红包出现异常_", json);
		}
		return Result.success(json);
	}
	
}
